import { defineStore } from 'pinia'
import { getSongUrlV1,getSongUrl } from '../api/song'
import { shuffle } from '../common/index'

export const useMusicStore = defineStore('music' , {
  state() {
    return {
      songUrl: '', // 歌曲url
      playType: 1, // 1 - 顺序 2 - 随机 3 - 单曲
      playUrls: [], // 歌曲url
      playMusic: {}, // 正在播放的歌曲
      progressVal: 0, // 进度条进度
      currentTime: 0, // 当前时间
      updateCurrentTime: 0, // 更新的当前时间
      duration: 0, // 总时间
      playList: [], // 歌曲列表
      toPlayList: [], // 随机歌曲
      isPlay: false, // 是否歌曲播放
      volume: 50, // 音量
    }
  },
  actions: {
    // 点击歌曲播放
    selectSongPlay(song) {
      const that = this
      that.isPlay = false
      const index = that.playList.findIndex(item => item.id === song.id)
      that.playMusic = song
      if(index !== -1) {
        that.songUrlV2(song.id)
        return
      }
      that.playList.push(song)
      that.toPlayList = shuffle(that.playList)
      that.songUrlV2(song.id)
    },
    // 下一首歌曲
    nextSong() {
      const that = this
      that.isPlay = false
      // 顺序播放
      if(that.playType === 1) {
        const index = that.playList.findIndex(item => item.id === that.playMusic.id)
        if((index + 1) >= that.playList.length) {
          that.playMusic = that.playList[0]
        }else {
          that.playMusic = that.playList[index + 1]
        }
        that.songUrlV2(that.playMusic.id)
        return
      }
      // 随机播放
      const index = that.toPlayList.findIndex(item => item.id === that.playMusic.id)
      if((index + 1) >= that.toPlayList.length) {
        that.playMusic = that.toPlayList[0]
      }else {
        that.playMusic = that.toPlayList[index + 1]
      }
      that.songUrlV2(that.playMusic.id)
    },
    // 上一首
    prevSong() {
      const that = this
      that.isPlay = false
      // 顺序播放
      if(that.playType === 1 || that.playType === 3) {
        const index = that.playList.findIndex(item => item.id === that.playMusic.id)
        if(index - 1 < 0) {
          that.playMusic = that.playList[that.playList.length - 1]
        }else {
          that.playMusic = that.playList[index - 1]
        }
        that.songUrlV2(that.playMusic.id)
        return
      }
      // 随机播放
      const index = that.toPlayList.findIndex(item => item.id === that.playMusic.id)
      if(index - 1 < 0) {
        that.playMusic = that.toPlayList[that.toPlayList.length - 1]
      }else {
        that.playMusic = that.toPlayList[index - 1]
      }
      that.songUrlV2(that.playMusic.id)
    },
    songUrlV1(songId , level) {
      getSongUrlV1(songId, level).then(res => {
        console.log(res);
      })
    },
    songUrlV2(songId) {
      const that = this
      getSongUrl(songId).then(res => {
        that.playUrls = res.data
        that.songUrl = res.data[0].url
        that.isPlay = true
      })
    }
  },
  persist: {
    key: 'musicStore'
  }
})
